package logic

import (
	"context"
	"errors"
	"zg2/cx_zy1/user_srv/cache"
	"zg2/cx_zy1/user_srv/models"

	"zg2/cx_zy1/user_srv/internal/svc"
	"zg2/cx_zy1/user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *user.LoginRequest) (*user.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var err error
	var u models.User
	u.Mobile = in.Mobile

	if err = u.GetUserByMobile(); err != nil {
		logx.Error("用户信息获取失败")
		return nil, errors.New("用户信息获取失败")
	}

	if u.ID == 0 {
		if err = u.Register(); err != nil {
			logx.Error("用户注册失败")
			return nil, errors.New("用户注册失败")
		}
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	
	if result != in.SmsCode {
		logx.Error("短信验证码错误")
		return nil, errors.New("短信验证码错误")
	}

	return &user.LoginResponse{
		UserId: int64(u.ID),
	}, nil
}
